var http = require('http')
var url = require('url')

function start() {
  const server = http.createServer(function (req, res) {
    //文件类型
    var type = req.url.substring(req.url.length - 4, req.url.length)
    //资源路径
    var fileName = __dirname + req.url
    //加载需要显示的图片资源
    if (type == '.jpg' || type == '.png') {
      res.writeHead(200, { 'Content-Type': 'text/' + type })
      res.end(fs.readFileSync(fileName))
    }

    // 加载首页
    var filePath = 'index.html'
    fs.stat(filePath, function (error, data) {
      if (error) {
        res.writeHead(404)
        res.end('404 Not Found.')
      } else {
        res.writeHead(200)
        fs.createReadStream(filePath).pipe(res)
      }
    })
  })

  server.listen(3001, 'localhost', () => {
    console.log(`Server running at http://localhost:3001/`)
  })
}

exports.start = start
